import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:permission_handler/permission_handler.dart' as permission_handler;
import '../values/constants.dart';

/// 权限管理服务
/// 
/// 提供统一的权限申请、检查和管理功能
/// 支持Android和iOS平台的各种系统权限
class PermissionService extends GetxService {
  // 权限申请结果统计
  final Map<Permission, PermissionStatus> _permissionResults = {};
  
  /// 初始化权限服务
  @override
  void onInit() {
    super.onInit();
    debugPrint('${Constants.permissionServiceTag}: 权限服务初始化');
  }

  /// 检查单个权限状态
  /// 
  /// [permission] 要检查的权限
  /// 返回权限状态
  Future<PermissionStatus> checkPermission(Permission permission) async {
    try {
      final status = await permission.status;
      debugPrint('${Constants.permissionServiceTag}: 检查权限 ${permission.toString()} - 状态: $status');
      return status;
    } catch (e) {
      debugPrint('${Constants.permissionServiceTag}: 检查权限失败 - ${permission.toString()}: $e');
      return PermissionStatus.denied;
    }
  }

  /// 申请单个权限
  /// 
  /// [permission] 要申请的权限
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestPermission(
    Permission permission, {
    bool showRationale = true,
  }) async {
    try {
      debugPrint('${Constants.permissionServiceTag}: 开始申请权限 - ${permission.toString()}');
      
      // 检查当前权限状态
      final currentStatus = await permission.status;
      debugPrint('${Constants.permissionServiceTag}: 当前权限状态 - $currentStatus');
      
      // 如果已经授权，直接返回
      if (_isPermissionGranted(currentStatus)) {
        debugPrint('${Constants.permissionServiceTag}: 权限已授权，无需申请');
        return PermissionRequestResult(
          permission: permission,
          status: currentStatus,
          isGranted: true,
          message: _getPermissionStatusMessage(currentStatus),
        );
      }
      
      // 如果权限被永久拒绝，提示用户去设置页面
      if (currentStatus == PermissionStatus.permanentlyDenied) {
        debugPrint('${Constants.permissionServiceTag}: 权限被永久拒绝，引导用户到设置页面');
        return _handlePermanentlyDenied(permission);
      }
      
      // 如果需要显示权限说明
      if (showRationale && currentStatus == PermissionStatus.denied) {
        final shouldRequest = await _showPermissionRationale(permission);
        if (!shouldRequest) {
          return PermissionRequestResult(
            permission: permission,
            status: PermissionStatus.denied,
            isGranted: false,
            message: '用户取消了权限申请',
          );
        }
      }
      
      // 申请权限
      final status = await permission.request();
      _permissionResults[permission] = status;
      
      debugPrint('${Constants.permissionServiceTag}: 权限申请结果 - ${permission.toString()}: $status');
      
      return PermissionRequestResult(
        permission: permission,
        status: status,
        isGranted: _isPermissionGranted(status),
        message: _getPermissionStatusMessage(status),
      );
      
    } catch (e) {
      debugPrint('${Constants.permissionServiceTag}: 权限申请异常 - ${permission.toString()}: $e');
      return PermissionRequestResult(
        permission: permission,
        status: PermissionStatus.denied,
        isGranted: false,
        message: '权限申请失败: ${e.toString()}',
      );
    }
  }

  /// 批量申请权限
  /// 
  /// [permissions] 要申请的权限列表
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果列表
  Future<List<PermissionRequestResult>> requestPermissions(
    List<Permission> permissions, {
    bool showRationale = true,
  }) async {
    debugPrint('${Constants.permissionServiceTag}: 开始批量申请权限 - 共${permissions.length}个');
    
    final results = <PermissionRequestResult>[];
    
    for (final permission in permissions) {
      final result = await requestPermission(permission, showRationale: showRationale);
      results.add(result);
      
      // 如果用户拒绝了某个权限，询问是否继续申请其他权限
      if (!result.isGranted && showRationale) {
        final shouldContinue = await _askContinueRequest(permission, permissions.length - results.length);
        if (!shouldContinue) {
          debugPrint('${Constants.permissionServiceTag}: 用户选择停止申请剩余权限');
          break;
        }
      }
    }
    
    debugPrint('${Constants.permissionServiceTag}: 批量权限申请完成 - 成功: ${results.where((r) => r.isGranted).length}/${results.length}');
    return results;
  }

  /// 检查多个权限状态
  /// 
  /// [permissions] 要检查的权限列表
  /// 返回权限状态映射
  Future<Map<Permission, PermissionStatus>> checkPermissions(
    List<Permission> permissions,
  ) async {
    debugPrint('${Constants.permissionServiceTag}: 批量检查权限状态 - 共${permissions.length}个');
    
    final results = <Permission, PermissionStatus>{};
    
    for (final permission in permissions) {
      final status = await checkPermission(permission);
      results[permission] = status;
    }
    
    return results;
  }

  /// 打开应用设置页面
  /// 
  /// 用于用户手动开启被永久拒绝的权限
  Future<bool> openAppSettings() async {
    try {
      debugPrint('${Constants.permissionServiceTag}: 打开应用设置页面');
      final result = await permission_handler.openAppSettings();
      debugPrint('${Constants.permissionServiceTag}: 打开设置页面结果: $result');
      return result;
    } catch (e) {
      debugPrint('${Constants.permissionServiceTag}: 打开设置页面失败: $e');
      return false;
    }
  }

  /// 获取所有已申请权限的统计信息
  Map<PermissionStatus, List<Permission>> getPermissionStats() {
    final stats = <PermissionStatus, List<Permission>>{
      PermissionStatus.granted: [],
      PermissionStatus.denied: [],
      PermissionStatus.permanentlyDenied: [],
      PermissionStatus.restricted: [],
      PermissionStatus.limited: [], // 添加limited状态统计
    };
    
    _permissionResults.forEach((permission, status) {
      stats[status]?.add(permission);
    });
    
    return stats;
  }

  /// 获取权限详细说明
  /// 
  /// 特别针对limited状态提供详细解释
  /// [permission] 权限类型
  /// [status] 权限状态
  /// 返回详细说明文本
  String getPermissionDetailedDescription(Permission permission, PermissionStatus status) {
    if (status == PermissionStatus.limited && permission == Permission.photos) {
      return '📸 iOS相册权限说明：\n\n'
             '✅ 当前状态：部分权限（可正常使用）\n'
             '📱 这意味着：\n'
             '  • 您选择了"选择照片"而非"允许访问所有照片"\n'
             '  • App只能访问您主动选择的照片\n'
             '  • 这是iOS 14+的隐私保护功能\n'
             '  • 您可以随时在相册中添加或移除可访问的照片\n\n'
             '🔧 如需访问全部照片：\n'
             '  设置 → 隐私与安全性 → 照片 → 选择"完全访问权限"';
    }
    
    return _getPermissionDescription(permission);
  }

  /// 清除权限申请历史
  void clearPermissionHistory() {
    debugPrint('${Constants.permissionServiceTag}: 清除权限申请历史');
    _permissionResults.clear();
  }

  // ==================== 专用权限申请方法 ====================

  /// 申请相册/照片权限
  /// 
  /// 自动处理不同平台的权限差异和fallback策略
  /// Android: photos -> storage (fallback)
  /// iOS: photos
  /// 
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestGalleryPermission({
    bool showRationale = true,
  }) async {
    try {
      debugPrint('${Constants.permissionServiceTag}: 开始申请相册权限');
      
      if (Platform.isAndroid) {
        // Android 平台：先检查是否已有任何可用的权限
        final photosStatus = await Permission.photos.status;
        final storageStatus = await Permission.storage.status;
        
        debugPrint('${Constants.permissionServiceTag}: Android平台权限状态检查 - photos: $photosStatus, storage: $storageStatus');
        
        // 如果photos权限可用（granted或limited），直接返回成功
        if (_isPermissionGranted(photosStatus)) {
          debugPrint('${Constants.permissionServiceTag}: Android photos权限已可用，无需申请');
          return PermissionRequestResult(
            permission: Permission.photos,
            status: photosStatus,
            isGranted: true,
            message: _getPermissionStatusMessage(photosStatus),
          );
        }
        
        // 如果storage权限可用，直接返回成功
        if (_isPermissionGranted(storageStatus)) {
          debugPrint('${Constants.permissionServiceTag}: Android storage权限已可用，无需申请');
          return PermissionRequestResult(
            permission: Permission.photos, // 统一返回photos权限类型
            status: PermissionStatus.granted,
            isGranted: true,
            message: '相册权限已授权（通过storage权限）',
          );
        }
        
        // 都没有权限时，优先申请photos权限
        debugPrint('${Constants.permissionServiceTag}: Android平台 - 申请photos权限');
        final photosResult = await requestPermission(Permission.photos, showRationale: showRationale);
        
        if (photosResult.isGranted) {
          debugPrint('${Constants.permissionServiceTag}: Android photos权限申请成功 (状态: ${photosResult.status})');
          return photosResult;
        }
        
        // 如果photos权限被永久拒绝，直接返回失败，不再尝试storage
        if (photosResult.status == PermissionStatus.permanentlyDenied) {
          debugPrint('${Constants.permissionServiceTag}: photos权限被永久拒绝，不再尝试storage权限');
          return photosResult;
        }
        
        // 只有在photos权限被普通拒绝时，才尝试storage权限（避免双重弹窗）
        if (photosResult.status == PermissionStatus.denied && showRationale) {
          debugPrint('${Constants.permissionServiceTag}: Android photos权限被拒绝，尝试storage权限作为fallback');
          final storageResult = await requestPermission(Permission.storage, showRationale: false); // 关闭storage的说明弹窗
          
          if (storageResult.isGranted) {
            debugPrint('${Constants.permissionServiceTag}: Android storage权限申请成功（fallback）');
            return PermissionRequestResult(
              permission: Permission.photos, // 统一返回photos权限类型
              status: PermissionStatus.granted,
              isGranted: true,
              message: '相册权限已授权（通过storage权限）',
            );
          }
        }
        
        // 权限申请失败
        debugPrint('${Constants.permissionServiceTag}: Android相册权限申请失败');
        return PermissionRequestResult(
          permission: Permission.photos,
          status: photosResult.status,
          isGranted: false,
          message: '相册权限被拒绝，无法选择照片',
        );
        
      } else if (Platform.isIOS) {
        // iOS 平台：直接申请photos权限
        debugPrint('${Constants.permissionServiceTag}: iOS平台 - 申请photos权限');
        final iosResult = await requestPermission(Permission.photos, showRationale: showRationale);
        
        debugPrint('${Constants.permissionServiceTag}: iOS photos权限申请结果: ${iosResult.isGranted}');
        return iosResult;
        
      } else {
        // 其他平台（如Web、Windows等）
        debugPrint('${Constants.permissionServiceTag}: 其他平台 - 尝试申请photos权限');
        return await requestPermission(Permission.photos, showRationale: showRationale);
      }
      
    } catch (e) {
      debugPrint('${Constants.permissionServiceTag}: 相册权限申请异常: $e');
      return PermissionRequestResult(
        permission: Permission.photos,
        status: PermissionStatus.denied,
        isGranted: false,
        message: '相册权限申请异常: ${e.toString()}',
      );
    }
  }

  /// 申请相机权限
  /// 
  /// 统一处理相机权限申请
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果
  Future<PermissionRequestResult> requestCameraPermission({
    bool showRationale = true,
  }) async {
    debugPrint('${Constants.permissionServiceTag}: 申请相机权限');
    return await requestPermission(Permission.camera, showRationale: showRationale);
  }

  /// 申请媒体权限组（相机 + 相册）
  /// 
  /// 同时申请相机和相册权限，适用于图片选择场景
  /// [showRationale] 是否显示权限说明对话框
  /// 返回权限申请结果列表
  Future<MediaPermissionResult> requestMediaPermissions({
    bool showRationale = true,
  }) async {
    debugPrint('${Constants.permissionServiceTag}: 开始申请媒体权限组（相机+相册）');
    
    try {
      // 申请相机权限
      final cameraResult = await requestCameraPermission(showRationale: showRationale);
      
      // 申请相册权限
      final galleryResult = await requestGalleryPermission(showRationale: showRationale);
      
      final hasAllPermissions = cameraResult.isGranted && galleryResult.isGranted;
      
      debugPrint('${Constants.permissionServiceTag}: 媒体权限申请完成 - 相机: ${cameraResult.isGranted}, 相册: ${galleryResult.isGranted}');
      
      return MediaPermissionResult(
        cameraResult: cameraResult,
        galleryResult: galleryResult,
        hasAllPermissions: hasAllPermissions,
      );
      
    } catch (e) {
      debugPrint('${Constants.permissionServiceTag}: 媒体权限申请异常: $e');
      
      final errorResult = PermissionRequestResult(
        permission: Permission.camera,
        status: PermissionStatus.denied,
        isGranted: false,
        message: '媒体权限申请异常: ${e.toString()}',
      );
      
      return MediaPermissionResult(
        cameraResult: errorResult,
        galleryResult: errorResult,
        hasAllPermissions: false,
      );
    }
  }

  // ==================== 私有方法 ====================

  /// 判断权限是否可用
  /// 
  /// 对于不同权限类型有不同的判断标准：
  /// - photos权限：granted 或 limited 都可以使用
  /// - 其他权限：只有granted才可以使用
  bool _isPermissionGranted(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return true;
      case PermissionStatus.limited:
        // limited状态对于photos权限是可用的（部分权限）
        return true;
      case PermissionStatus.denied:
      case PermissionStatus.permanentlyDenied:
      case PermissionStatus.restricted:
      case PermissionStatus.provisional:
        return false;
    }
  }

  // 私有方法：处理永久拒绝的权限
  Future<PermissionRequestResult> _handlePermanentlyDenied(Permission permission) async {
    final shouldOpenSettings = await Get.dialog<bool>(
      AlertDialog(
        title: Text('需要开启${_getPermissionDisplayName(permission)}权限'),
        content: Text(
          '该权限已被永久拒绝，需要在设置中手动开启。\n\n'
          '操作步骤：\n'
          '1. 点击"前往设置"\n'
          '2. 找到权限管理\n'
          '3. 开启${_getPermissionDisplayName(permission)}权限',
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('前往设置'),
          ),
        ],
      ),
    ) ?? false;

    if (shouldOpenSettings) {
      await permission_handler.openAppSettings();
    }

    return PermissionRequestResult(
      permission: permission,
      status: PermissionStatus.permanentlyDenied,
      isGranted: false,
      message: shouldOpenSettings ? '已引导用户到设置页面' : '用户取消前往设置',
    );
  }

  // 私有方法：显示权限申请说明
  Future<bool> _showPermissionRationale(Permission permission) async {
    return await Get.dialog<bool>(
      AlertDialog(
        title: Text('需要${_getPermissionDisplayName(permission)}权限'),
        content: Text(_getPermissionDescription(permission)),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('拒绝'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('允许'),
          ),
        ],
      ),
    ) ?? false;
  }

  // 私有方法：询问是否继续申请权限
  Future<bool> _askContinueRequest(Permission rejectedPermission, int remainingCount) async {
    if (remainingCount <= 0) return false;
    
    return await Get.dialog<bool>(
      AlertDialog(
        title: const Text('权限申请'),
        content: Text(
          '${_getPermissionDisplayName(rejectedPermission)}权限被拒绝。\n\n'
          '还有${remainingCount}个权限需要申请，是否继续？',
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('停止申请'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('继续申请'),
          ),
        ],
      ),
    ) ?? false;
  }

  // 私有方法：获取权限显示名称
  String _getPermissionDisplayName(Permission permission) {
    switch (permission) {
      case Permission.camera:
        return '相机';
      case Permission.microphone:
        return '麦克风';
      case Permission.location:
      case Permission.locationAlways:
      case Permission.locationWhenInUse:
        return '位置';
      case Permission.storage:
      case Permission.photos:
      case Permission.mediaLibrary:
        return '存储';
      case Permission.notification:
        return '通知';
      case Permission.contacts:
        return '通讯录';
      case Permission.phone:
        return '电话';
      case Permission.sms:
        return '短信';
      case Permission.sensors:
        return '传感器';
      case Permission.calendar:
        return '日历';
      default:
        return permission.toString().split('.').last;
    }
  }

  // 私有方法：获取权限描述
  String _getPermissionDescription(Permission permission) {
    switch (permission) {
      case Permission.camera:
        return '应用需要访问您的相机，用于拍照和扫码等功能。';
      case Permission.microphone:
        return '应用需要访问您的麦克风，用于录音和语音通话等功能。';
      case Permission.location:
      case Permission.locationAlways:
      case Permission.locationWhenInUse:
        return '应用需要访问您的位置信息，用于提供基于位置的服务。';
      case Permission.storage:
      case Permission.photos:
      case Permission.mediaLibrary:
        return '应用需要访问您的存储空间，用于保存和读取文件。';
      case Permission.notification:
        return '应用需要发送通知的权限，用于及时提醒您重要信息。';
      case Permission.contacts:
        return '应用需要访问您的通讯录，用于联系人相关功能。';
      case Permission.phone:
        return '应用需要访问电话权限，用于拨打电话等功能。';
      case Permission.sms:
        return '应用需要访问短信权限，用于发送验证码等功能。';
      case Permission.sensors:
        return '应用需要访问传感器权限，用于运动检测等功能。';
      case Permission.calendar:
        return '应用需要访问日历权限，用于日程管理等功能。';
      default:
        return '应用需要此权限以正常运行，请允许权限申请。';
    }
  }

  // 私有方法：获取权限状态消息
  String _getPermissionStatusMessage(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return '权限已授权';
      case PermissionStatus.limited:
        return '权限已授权（iOS选择照片模式）'; // 更清晰地说明这是iOS的正常功能
      case PermissionStatus.denied:
        return '权限被拒绝';
      case PermissionStatus.permanentlyDenied:
        return '权限被永久拒绝，需要在设置中手动开启';
      case PermissionStatus.restricted:
        return '权限受限制';
      case PermissionStatus.provisional:
        return '临时权限';
    }
  }
}

/// 权限申请结果
class PermissionRequestResult {
  /// 权限类型
  final Permission permission;
  
  /// 权限状态
  final PermissionStatus status;
  
  /// 是否已授权
  final bool isGranted;
  
  /// 结果消息
  final String message;

  const PermissionRequestResult({
    required this.permission,
    required this.status,
    required this.isGranted,
    required this.message,
  });

  @override
  String toString() {
    return 'PermissionRequestResult{'
        'permission: $permission, '
        'status: $status, '
        'isGranted: $isGranted, '
        'message: $message'
        '}';
  }
}

/// 媒体权限申请结果
/// 
/// 包含相机和相册权限的申请结果
class MediaPermissionResult {
  /// 相机权限申请结果
  final PermissionRequestResult cameraResult;
  
  /// 相册权限申请结果
  final PermissionRequestResult galleryResult;
  
  /// 是否拥有所有权限
  final bool hasAllPermissions;

  const MediaPermissionResult({
    required this.cameraResult,
    required this.galleryResult,
    required this.hasAllPermissions,
  });

  /// 是否拥有相机权限
  bool get hasCameraPermission => cameraResult.isGranted;
  
  /// 是否拥有相册权限
  bool get hasGalleryPermission => galleryResult.isGranted;

  @override
  String toString() {
    return 'MediaPermissionResult{'
        'camera: ${cameraResult.isGranted}, '
        'gallery: ${galleryResult.isGranted}, '
        'hasAll: $hasAllPermissions'
        '}';
  }
}

/// 预定义的权限组
class PermissionGroups {
  /// 基础权限组（相机、相册、位置）
  static const List<Permission> basic = [
    Permission.camera,
    Permission.photos,
    Permission.location,
  ];
  
  /// 媒体权限组（相机、麦克风、相册）
  static const List<Permission> media = [
    Permission.camera,
    Permission.microphone,
    Permission.photos,
  ];
  
  /// 通讯权限组（通讯录、电话、短信）
  static const List<Permission> communication = [
    Permission.contacts,
    Permission.phone,
    Permission.sms,
  ];
  
  /// 全部常用权限
  static const List<Permission> all = [
    Permission.camera,
    Permission.microphone,
    Permission.location,
    Permission.photos,
    Permission.notification,
    Permission.contacts,
    Permission.phone,
  ];
}
